import { Base64 } from "js-base64";
import { sm3, sm2 } from "sm-crypto";
import urlQuery from "./urlQuery";
import msgAlert from "./msgAlert";
import vConsole from "./vConsole";
import getRand from "./getRand";
import axios from "../../axios";
import i18n from "i18next";

const { t } = i18n;

const params_obj = urlQuery(window.location.href);
let company = params_obj["u"];

const relogin = () => {
  console.log("重新登陆");
  if (window.location.href.split("#/")[1] === "login") {
    window.location.reload();
  } else {
    let href = window.location.href.split("#/")[0];
    console.log(`${href}#/login`);
    window.location.replace(`${href}#/login`);
  }
};

//封装axios
 const postAxios = (method, action, params, others) => {
  const publicKey =
    "0459bb6f796c205b835f43b48dcda4e62d52675420bca95be06732f4e3f23830f5cdb1a19a4d56ab391bd3052d3e7c3bc0cf9ceb2859a91e5ef4f0f3d0ea200eff";
  const privceKey =
    "bf446d73aab5e3b8481271cf3da9d58f313f37646aa2ede13180565eb031ea67";
  const cipherMode = 1;

  const language = company !== "mg" ? "cn" : "en";
  const timestamp = new Date().getTime();
  const rank_num = getRand(64);
  const nonce = rank_num;
  const session_id =
    method === "login.web" || method === "VI_login.web"
      ? rank_num
      : sessionStorage.getItem("session_id");
  const base64_params = Base64.encode(encodeURI(JSON.stringify(params)));
  const body = "04" + sm2.doEncrypt(base64_params, publicKey, cipherMode); // sm2加密;
  const sign = sm3(timestamp + "\n" + nonce + "\n" + body + "\n" + session_id);
  const headers = {
    timestamp,
    nonce,
    session_id,
    sign,
    language,
    "Content-Type": "application/json;charset=UTF-8",
  };

  if (!session_id) {
    relogin();
    return;
  }
  let req_url = "";
  if (method.indexOf("/") > -1) {
    //修改request_type
    req_url = `/mega/v3/${method}/${action}/gateway`;
  } else {
    req_url = `/mega/v3/web/${method}/${action}/gateway`;
  }
  return new Promise((resolve) => {
    axios
      .post(req_url, body, { headers })
      .then((res) => {
        res = {
          data: JSON.parse(
            decodeURIComponent(
              Base64.decode(
                sm2.doDecrypt(res.data.substring(2), privceKey, cipherMode)
              )
            )
          ),
        };
        vConsole([method + "/" + action, params, headers, res]);

        if (method === "login.web" || method === "VI_login.web") {
          resolve(res.data);
          return;
        }
        if (res.data.flag === "0000") {
          resolve(res.data);
        } else if (res.data.flag === "1109") {
          relogin();
        } else if (res.data.flag === "1125") {
          resolve(res.data);
        } else {
          let data =
            res.data.data && res.data.data !== null
              ? JSON.stringify(res.data.data)
              : "";
          let msg = company === "mg" ? res.data.msg_en : res.data.msg_cn;
          msgAlert(res.data.flag, msg, data);
          resolve(false);
        }
      })
      .catch((err) => {
        vConsole([err]);
        msgAlert(
          "500",
          t("common.error_info"),
          "System under deployment, please try again later."
        );
        resolve(false);
      });
  });
};

export default postAxios
